package order

import (
	"counter-help/admin/server/global"
	"counter-help/admin/server/model/customer"
	oreq "counter-help/admin/server/model/order/request"
	oresp "counter-help/admin/server/model/order/response"
	"errors"
	"fmt"
)

type OrderService struct {
}

const (
	SUCCESS = iota + 1
	Failure
	Complete = 3
	AFTER    = 4
)

func (s *OrderService) OrderList(info *oreq.OrderListSearch) (list interface{}, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	var status int

	if info.Type == SUCCESS {
		status = 4 // 排单完成
	} else if info.Type == Failure {
		status = 3 // 排单未完成
	} else if info.Type == Complete {
		status = 5
	} else {
		return nil, 0, errors.New("参数 Type 无法识别")
	}

	var respList []oresp.OrderListResp

	// 获取订单列表信息
	var orderList []customer.CusOrder
	db := global.GVA_DB.Model(&customer.CusOrder{})

	// 获取符合条件的订单总数
	err = db.Where("status = ?", status).Count(&total).Error
	if err != nil {
		return nil, 0, errors.New("获取订单总数失败: " + err.Error())
	}

	// 分页查询订单列表
	err = db.Where("status = ?", status).Limit(limit).Offset(offset).Order("id").Find(&orderList).Error
	if err != nil {
		return nil, 0, errors.New("获取订单列表失败: " + err.Error())
	}

	// 遍历订单列表，填充响应数据
	for _, order := range orderList {
		var resp oresp.OrderListResp

		// 填充订单相关信息
		resp.OrderId = int(order.ID)
		resp.Require = order.AnRequire   // 分析需求
		resp.MaxPrice = *order.BudgetMax // 最大价格
		resp.MinPrice = *order.BudgetMin // 最小价格
		resp.UpdatedAt = order.UpdatedAt
		resp.Deadline = order.Deadline
		resp.Other = order.Other // 时间要求
		resp.Title = order.Title

		// 根据 order.OrderUserId 获取需求发布人名称
		var pubUserInfo customer.CusUser
		err = global.GVA_DB.Model(&customer.CusUser{}).Where("id = ?", order.OrderUserId).First(&pubUserInfo).Error
		if err != nil {
			return nil, 0, errors.New(fmt.Sprintf("获取发布用户信息失败！订单ID: %d, 错误: %v", order.ID, err))
		}
		resp.Publisher = pubUserInfo.Nickname

		// 根据 order.ID 获取候选人信息
		var assignInfo []customer.CusOrderAssignments
		err = global.GVA_DB.Model(&customer.CusOrderAssignments{}).Where("order_id = ?", order.ID).Find(&assignInfo).Error
		if err != nil {
			return nil, 0, errors.New(fmt.Sprintf("获取候选人信息失败！订单ID: %d, 错误: %v", order.ID, err))
		}

		// 构建候选人信息列表
		var candidates []oresp.CandidateInfo
		for _, assign := range assignInfo {
			var candidate customer.CusUser
			err = global.GVA_DB.Model(&customer.CusUser{}).Where("id = ?", assign.UserId).First(&candidate).Error
			if err != nil {
				return nil, 0, errors.New(fmt.Sprintf("获取候选人信息失败！候选人ID: %d, 错误: %v", assign.UserId, err))
			}

			// 获取候选人的订单统计信息
			var totalOrders, completedOrders, ongoingOrders int64

			// 获取总接单数
			err = global.GVA_DB.Model(&customer.CusOrderAssignments{}).
				Where("user_id = ?", candidate.ID).
				Count(&totalOrders).Error
			if err != nil {
				global.GVA_LOG.Error(fmt.Sprintf("获取候选人总接单数失败！候选人ID: %d", candidate.ID))
				totalOrders = 0
			}

			// 获取已完成订单数
			err = global.GVA_DB.Model(&customer.CusOrderAssignments{}).
				Joins("LEFT JOIN cus_orders ON cus_order_assignments.order_id = cus_orders.id").
				Where("cus_order_assignments.user_id = ? AND cus_orders.status = ?", candidate.ID, 5).
				Count(&completedOrders).Error
			if err != nil {
				global.GVA_LOG.Error(fmt.Sprintf("获取候选人已完成订单数失败！候选人ID: %d", candidate.ID))
				completedOrders = 0
			}

			// 获取进行中订单数
			err = global.GVA_DB.Model(&customer.CusOrderAssignments{}).
				Joins("LEFT JOIN cus_orders ON cus_order_assignments.order_id = cus_orders.id").
				Where("cus_order_assignments.user_id = ? AND cus_orders.status != ? AND cus_orders.status != ?",
					candidate.ID, 5, 3). // 排除已完成(5)和未完成(3)状态
				Count(&ongoingOrders).Error
			if err != nil {
				global.GVA_LOG.Error(fmt.Sprintf("获取候选人进行中订单数失败！候选人ID: %d", candidate.ID))
				ongoingOrders = 0
			}

			// 填充候选人信息
			candidateInfo := oresp.CandidateInfo{
				ID:              candidate.ID,
				Nickname:        candidate.Nickname,
				Phone:           candidate.Phone,
				TotalOrders:     totalOrders,     // 添加总接单数
				CompletedOrders: completedOrders, // 添加已完成订单数
				OngoingOrders:   ongoingOrders,   // 添加进行中订单数
			}

			candidates = append(candidates, candidateInfo)
		}

		// 将候选人信息添加到响应数据中
		resp.Candidates = candidates

		// 将结果追加到响应列表中
		respList = append(respList, resp)
	}

	return respList, total, nil
}

func (s *OrderService) MatchedOrderList(info *oreq.OrderListSearch) (list interface{}, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	var status int

	if info.Type == SUCCESS {
		status = 4 // 排单完成
	} else if info.Type == Failure {
		status = 3 // 排单未完成
	} else if info.Type == Complete {
		status = 5
	} else if info.Type == AFTER {
		status = 6
	} else {
		return nil, 0, errors.New("参数 Type 无法识别")
	}

	var respList []oresp.MatchedOrderListResp

	// 获取订单列表信息
	var orderList []customer.CusOrder
	db := global.GVA_DB.Model(&customer.CusOrder{})

	// 获取符合条件的订单总数
	err = db.Where("status = ?", status).Count(&total).Error
	if err != nil {
		return nil, 0, errors.New("获取订单总数失败: " + err.Error())
	}

	// 分页查询订单列表
	err = db.Where("status = ?", status).Limit(limit).Offset(offset).Order("id").Find(&orderList).Error
	if err != nil {
		return nil, 0, errors.New("获取订单列表失败: " + err.Error())
	}

	// 遍历订单列表，填充响应数据
	for _, order := range orderList {
		var resp oresp.MatchedOrderListResp

		// 填充订单相关信息
		resp.OrderId = int(order.ID)
		resp.Require = order.AnRequire // 分析需求
		resp.IsPaid = order.IsPaid
		resp.UpdatedAt = order.UpdatedAt
		resp.Deadline = order.Deadline
		resp.ExPrice = *order.ExPrice // 成交价格
		resp.Other = order.Other      // 时间要求
		resp.Title = order.Title

		// 根据 order.OrderUserId 获取需求发布人名称
		var pubUserInfo customer.CusUser
		err = global.GVA_DB.Model(&customer.CusUser{}).Where("id = ?", order.OrderUserId).First(&pubUserInfo).Error
		if err != nil {
			return nil, 0, errors.New(fmt.Sprintf("获取发布用户信息失败！订单ID: %d, 错误: %v", order.ID, err))
		}
		resp.Publisher = pubUserInfo.Nickname

		// 根据 order.ID 获取候选人信息
		var assignInfo []customer.CusOrderAssignments
		err = global.GVA_DB.Model(&customer.CusOrderAssignments{}).Where("order_id = ?", order.ID).Find(&assignInfo).Error
		if err != nil {
			return nil, 0, errors.New(fmt.Sprintf("获取候选人信息失败！订单ID: %d, 错误: %v", order.ID, err))
		}

		// 构建候选人信息列表
		var candidates []oresp.CandidateInfo
		for _, assign := range assignInfo {
			var candidate customer.CusUser
			err = global.GVA_DB.Model(&customer.CusUser{}).Where("id = ?", assign.UserId).First(&candidate).Error
			if err != nil {
				return nil, 0, errors.New(fmt.Sprintf("获取候选人信息失败！候选人ID: %d, 错误: %v", assign.UserId, err))
			}

			// 填充候选人信息
			candidateInfo := oresp.CandidateInfo{
				ID:       candidate.ID,
				Nickname: candidate.Nickname,
				Phone:    candidate.Phone,
			}

			// 将候选人信息追加到候选人列表中
			candidates = append(candidates, candidateInfo)
		}

		// 将候选人信息添加到响应数据中
		resp.Candidates = candidates

		// 将结果追加到响应列表中
		respList = append(respList, resp)
	}

	return respList, total, nil
}

func (s *OrderService) UpdateUnFinishOrder(updateInfo *oreq.UpdateUnFinishOrderReq) (err error) {
	// 更新最终接单人
	err = global.GVA_DB.Model(&customer.CusOrderAssignments{}).
		Where("order_id = ?", updateInfo.OrderId).
		Where("user_id = ?", updateInfo.UserId).
		Update("is_final", 1).Error
	if err != nil {
		return fmt.Errorf("更新最终接单人错误, 订单号: %d, 最终接单人: %d, 错误: %v",
			updateInfo.OrderId, updateInfo.UserId, err)
	}

	// 删除其他非最终接单人的记录
	err = global.GVA_DB.Model(&customer.CusOrderAssignments{}).
		Where("order_id = ?", updateInfo.OrderId).
		Where("is_final = ?", 0).
		Delete(&customer.CusOrderAssignments{}).Error
	if err != nil {
		return fmt.Errorf("删除非最终接单人错误, 订单号: %d, 最终接单人: %d, 错误: %v",
			updateInfo.OrderId, updateInfo.UserId, err)
	}

	// 更新订单价格和状态
	err = global.GVA_DB.Model(&customer.CusOrder{}).
		Where("id = ?", updateInfo.OrderId).
		Updates(map[string]interface{}{
			"ex_price": updateInfo.Price,
			"status":   4,
		}).Error
	if err != nil {
		return fmt.Errorf("更新订单价格错误, 订单号: %d, 最终接单人: %d, 错误: %v",
			updateInfo.OrderId, updateInfo.UserId, err)
	}

	return nil
}

const (
	FINISH = iota
	REPUBLIC
	INNER
	DELETE
)

func (s *OrderService) UpdateFinishOrder(updateInfo *oreq.UpdateFinishOrderResp) (err error) {
	if updateInfo.Type == FINISH {
		// 订单完成
		err = global.GVA_DB.
			Model(&customer.CusOrder{}).
			Where("id = ?", updateInfo.OrderId).
			Update("status", 5).Error
		if err != nil {
			return errors.New("FINISH 订单完成数据库操作有误！")
		}

		// 更新 CusOrderAssignments 表的 is_final 字段
		err = global.GVA_DB.
			Model(&customer.CusOrderAssignments{}).
			Where("order_id = ?", updateInfo.OrderId).
			Update("is_final", 1).Error
		if err != nil {
			return errors.New("FINISH 更新 CusOrderAssignments 的 is_final 字段失败！")
		}

	} else if updateInfo.Type == REPUBLIC {
		// 订单失败 重新发布
		err = global.GVA_DB.Model(&customer.CusOrderAssignments{}).
			Where("order_id = ? AND deleted_at IS NULL", updateInfo.OrderId).Delete(&customer.CusOrderAssignments{}).Error
		if err != nil {
			return errors.New("REPUBLIC 删除接单信息错误！")
		}
		// 订单重新发布
		err = global.GVA_DB.Model(&customer.CusOrder{}).
			Where("id = ?", updateInfo.OrderId).
			Update("status", 3).Error
		if err != nil {
			return errors.New("REPUBLIC 订单重新排单 数据库操作有误！")
		}
	} else if updateInfo.Type == INNER {
		// 订单失败 内部接单

		// 1. 通过 phone 查询 CusUser 表获取 userId
		var cusUser customer.CusUser
		err = global.GVA_DB.Model(&customer.CusUser{}).
			Where("phone = ?", updateInfo.Phone).First(&cusUser).Error
		if err != nil {
			return errors.New("INNER 查询用户信息失败！")
		}

		// 2. 将查询到的 userId 赋值给 cusAssign
		var cusAssign customer.CusOrderAssignments
		cusAssign.OrderId = &updateInfo.OrderId

		// 将 *uint 转换为 *int
		userID := int(cusUser.ID)
		cusAssign.UserId = &userID // 使用转换后的 *int

		// 3. 将 cusAssign 信息写入 CusOrderAssignments 表
		err = global.GVA_DB.Model(&customer.CusOrderAssignments{}).Create(&cusAssign).Error
		if err != nil {
			return errors.New("INNER 更新内部人员操作失败！")
		}
	} else if updateInfo.Type == DELETE {
		// 订单失败 订单删除
		err = global.GVA_DB.Model(&customer.CusOrder{}).Where("order_id = ?", updateInfo.OrderId).Delete(&customer.CusOrder{}).Error
		if err != nil {
			return errors.New("DELETE 删除订单操作失败！")
		}
		// 删除接单信息
		err = global.GVA_DB.Model(&customer.CusOrderAssignments{}).
			Where("order_id = ?", updateInfo.OrderId).
			Delete(&customer.CusOrderAssignments{}).Error
		if err != nil {
			return errors.New("DELETE 删除接单信息操作失败！")
		}
	}
	return nil
}

// AddPrice 增款
func (s *OrderService) AddPrice(priceInfo *oreq.AddPriceReq) (err error) {
	err = global.GVA_DB.Model(&customer.CusOrder{}).Where("id = ?", priceInfo.OrderId).Update("add_price", priceInfo.Money).Error
	if err != nil {
		return errors.New("更新增款失败")
	}
	return
}
func (s *OrderService) AfterSalesOrder(priceInfo *oreq.AfterSalesOrderResp) (err error) {
	// 通过 OrderId 更新 status 字段
	db := global.GVA_DB.Model(&customer.CusOrder{}).
		Where("id = ?", priceInfo.OrderId).
		Update("status", 5)

	// 如果传递了价格信息，则更新 ex_price 字段
	if priceInfo.Price != 0 {
		db = db.Update("ex_price", priceInfo.Price)
	}

	// 执行更新操作并检查错误
	if err = db.Error; err != nil {
		return errors.New("退款操作失败")
	}
	return
}

func (s *OrderService) CreateSalesOrder(priceInfo *oreq.CreateAfterSalesOrderResp) (err error) {
	// 通过 OrderId 更新 status 字段
	db := global.GVA_DB.Model(&customer.CusOrder{}).
		Where("id = ?", priceInfo.OrderId).
		Update("status", priceInfo.Status)

	// 执行更新操作并检查错误
	if err = db.Error; err != nil {
		return errors.New("退款操作失败")
	}
	return
}

func (s *OrderService) SubPrice(priceInfo *oreq.SubPriceReq) (err error) {
	err = global.GVA_DB.Model(&customer.CusOrder{}).Where("id = ?", priceInfo.OrderId).Update("refund_price", priceInfo.Money).Error
	if err != nil {
		return errors.New("更新减款失败")
	}
	return
}
